<template>
  <div id="save">
    <header class="px-3 py-2 border-bottom">
      <nav class="d-flex">
        <Button type="primary" icon="ios-search" class="mr-2" @click="upload"
          >上传</Button
        >
        <Button icon="ios-search" class="mr-2" @click="createDir"
          >新建文件夹</Button
        >
        <Button
          icon="ios-search"
          class="mr-2"
          v-if="checkedTrueLength"
          @click="downloadMany"
          >下载</Button
        >
        <Button
          icon="ios-search"
          class="mr-2"
          v-if="checkedTrueLength == 1"
          @click="shareFile(false)"
          >分享</Button
        >
        <Button
          icon="ios-search"
          class="mr-2"
          v-if="checkedTrueLength == 1"
          @click="rename(false)"
          >重命名</Button
        >
        <Button
          icon="ios-search"
          class="mr-2"
          v-if="checkedTrueLength"
          @click="del(false)"
          >删除</Button
        >
        <Input
          search
          enter-button
          placeholder="请输入关键词"
          class="ml-auto"
          @on-search="searchFile"
        />
      </nav>
      <Checkbox :value="checkedStatus" class="mt-3" @on-change="changeAll"
        ><span class="ml-2">全选</span></Checkbox
      >
    </header>
    <article>
      <list
        :item="item"
        v-for="item in list"
        :key="item.id"
        @changeSingle="changeSingle"
      />
    </article>
    <Page :total="100" show-sizer class="px-3 py-3" />
    <div class="images d-none" v-viewer="{ movable: false }">
      <img v-for="(src, index) in images" :src="src.url" :key="index" />
    </div>
    <Modal
      v-model="uploadModal"
      fullscreen
      title="上传文件"
      footer-hide
      @on-cancel="cancel"
    >
      <Upload
        multiple
        type="drag"
        action="/dev/upload?file_id=0"
        :headers="{ token }"
      >
        <div style="padding: 20px 0">
          <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
          <p>单击或拖动文件上传</p>
        </div>
      </Upload>
    </Modal>
  </div>
</template>

<script>
import List from "@/components/list";
import saveApi from "../api/save";

export default {
  components: {
    list: List,
  },
  data() {
    return {
      list: [
        // {
        //   type: "dir",    
        //   name: "我的笔记",
        //   create_time: "2019-12-15 08:00",
        //   checked: false,
        // },
      ],
      value: "",
      // 上传窗口
      uploadModal: false,
      token: "",
    };
  },
  methods: {
    // 全选
    changeAll(e) {
      this.list.map((item) => (item.checked = e));
    },
    // 子组件传递事件
    changeSingle(data) {
      switch (data.type) {
        case "checked":
          this.list.filter((item) => item.id == data.item.id)[0].checked =
            data.item.checked;
          break;
        case "delete":
          this.del(data.item.id);
          break;
        case "rename":
          this.rename(data.item.id);
          break;
        case "image":
          const viewer = this.$el.querySelector(".images").$viewer;
          const index = this.images.findIndex((item) => item.url == data.url);
          //通过传递的图片所在数组的下标,显示对应下标的图片
          viewer.view(index);
          viewer.show();
          break;
        case "download":
          this.downloadFile(data.item.url, data.item.name);
          break;
        case "share":
          this.shareFile(data.item.id);
          break;

        default:
          break;
      }
    },
    // 删除
    del(id) {
      let ids =
        id == false ? this.checkedTrue.map((item) => item.id).join(",") : id;
      this.$Modal.confirm({
        title: "提示",
        content: "是否要删除当前选中",
        onOk: () => {
          saveApi
            .deleteFile(ids)
            .then((response) => {
              if (response.status == 200) {
                this.getFileList();
                this.$Message.success("已删除");
              }
            })
            .catch((error) => console.log(error));
        },
      });
    },
    // 重命名
    rename(id) {
      let item =
        id === false
          ? this.checkedTrue[0]
          : this.list.filter((item) => item.id == id)[0];
      let value = item.name;
      this.$Modal.confirm({
        render: (h) => {
          return h("Input", {
            props: {
              value: value,
              autofocus: true,
              placeholder: "请填写新的名称...",
            },
            on: {
              input: (val) => {
                this.value = val;
              },
            },
          });
        },
        onOk: () => {
          saveApi
            .renameFile(item.id, this.value)
            .then((response) => {
              if (response.status == 200) {
                this.getFileList();
                this.$Message.success("重命名成功");
              }
            })
            .catch((error) => console.log(error));
        },
      });
    },

    // 处理请求到数据格式
    formatList(list) {
      const newList = list.map((item) => {
        item.type =
          item.ext == "" ? "dir" : item.ext.substring(0, item.ext.indexOf("/"));
        item.checked = false;
        return item;
      });
      return newList;
    },
    // 获取文件列表
    getFileList() {
      saveApi.getFileList().then((response) => {
        if (response.status == 200) {
          this.list = this.formatList(response.data.data);
        }
      });
    },
    // 创建文件夹
    createDir() {
      let value = "";
      this.$Modal.confirm({
        title: "新建文件夹",
        render: (h) => {
          return h("Input", {
            props: {
              value: value,
              autofocus: true,
              placeholder: "请输入文件夹名称...",
            },
            on: {
              input: (val) => {
                value = val;
              },
            },
          });
        },
        onOk: () => {
          saveApi
            .createDir(0, value)
            .then((response) => {
              if (response.status == 200) {
                this.getFileList();
                this.$Message.success("添加成功");
              }
            })
            .catch((error) => console.log(error));
        },
      });
    },
    // 上传文件
    upload() {
      this.uploadModal = true;
      this.token = localStorage.getItem("token");
    },
    // 关闭上传弹窗
    cancel() {
      this.getFileList();
      this.$Message.success("上传成功");
    },
    // 搜索
    searchFile(keyword) {
      if (keyword == "") {
        this.getFileList();
        return;
      }
      saveApi.searchFile(keyword).then((response) => {
        if (response.status == 200) {
          this.list = this.formatList(response.data.data.rows);
        }
      });
    },
    // 下载文件
    downloadFile(url, name) {
      url = url.replace(
        "http://demo-mp3.oss-cn-shenzhen.aliyuncs.com/egg-oss-demo",
        "/load"
      );
      saveApi.downloadFile(url).then((response) => {
        if (!response.data) return;
        // 将 blob对象转化为下载 url地址
        let url = window.URL.createObjectURL(new Blob([response.data]));
        let link = window.document.createElement("a");
        link.href = url;
        link.setAttribute("download", name);
        link.style.dispaly = "none";
        document.body.appendChild(link);
        // 给a标签绑定点击事件
        link.click();
      });
    },
    // 下载多个文件
    downloadMany() {
      this.checkedTrue
        .filter((item) => item.isdir != 1)
        .forEach((item) => this.downloadFile(item.url));
    },
    // 分享
    shareFile(id) {
      let shareId = id == false ? this.checkedTrue[0].id : id;
      this.$Modal.confirm({
        title: "分享",
        content: "<p>是否要创建分享链接？</p>",
        onOk: () => {
          saveApi
            .shareFile(shareId)
            .then((response) => {
              if (response.status == 200) {
                this.$Modal.success({
                  width: "40%",
                  title: "创建成功",
                  okText: "复制链接",
                  content: `<p>${response.data.data}</p>`,
                  onOk: () => {
                    // 复制链接
                    this.$clipboard(
                      response.data.data.replace("分享链接：", "")
                    );
                    this.$Message.success("复制成功");
                  },
                });
              }
            })
            .catch((error) => console.log(error));
        },
      });
    },
  },
  computed: {
    // checked为 true 的数组
    checkedTrue() {
      return this.list.filter((item) => item.checked == true);
    },
    // checked为 true 的长度
    checkedTrueLength() {
      return this.list.filter((item) => item.checked == true).length;
    },
    // 全选框的状态
    checkedStatus() {
      return this.checkedTrueLength == this.list.length;
    },
    // 图片缩放
    images() {
      const urls = [];
      this.list.forEach((item) => {
        if (item.type == "image") {
          urls.push(item);
        }
      });
      return urls;
    },
  },
  created() {
    this.getFileList();
  },
};
</script>

<style lang="scss" scoped>
#save {
  position: relative;
  width: 100%;
  height: 100%;
}
.ivu-input-wrapper {
  width: 220px;
}
article {
  position: absolute;
  top: 94px;
  bottom: 60px;
  width: 100%;
  overflow: auto;
  // background: url("https://tangzhe123-com.oss-cn-shenzhen.aliyuncs.com/Appstatic/qsbk/demo/datapic/1.jpg")
  //   no-repeat;
  // background-size: cover;
}
.ivu-page {
  position: absolute;
  bottom: 0;
  left: 0;
}
img {
  width: 100%;
  height: 100%;
}
</style>
